package com.caifu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.excel.CellSheetWriteHandler;
import com.caifu.excel.CustomHandler;
import com.caifu.excel.shopExcel.ExcelYsShop;
import com.caifu.excel.shopExcel.ExcelYsShopError;
import com.caifu.excel.shopExcel.ShopCommentWriteHandler;
import com.caifu.excel.shopExcel.ShopSpinnerWriteHandler;
import com.caifu.service.ReportRecordService;
import com.caifu.util.CheckUtil;
import com.caifu.vo.ReportRecordPageVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.web.servlet.ModelAndView;

/**
 * ClassName : ReportController
 *
 * @author :  yb
 * @description ：
 * @date : 2021-03-01 16:45
 */
@Controller
@RequestMapping("/report")
public class ReportController {

    @Resource
    private ReportRecordService reportRecordService;


    /**
     * 跳转 报表列表  页面
     *
     * @return ModelAndView
     */
    @GetMapping(value = "jumpReportListPage")
    public ModelAndView jumpReportListPage() {
        ModelAndView modelAndView = new ModelAndView();
        try {
            modelAndView.setViewName("report/batch_import");
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("error/error");
        }
        return modelAndView;
    }


    /**
     * 商铺 模板 导出
     *
     * @param response response
     */
    @GetMapping(value = "getShopReportTemplate", headers = "Accept=application/octet-stream")
    @ResponseBody
    public void getShopReportTemplate(HttpServletResponse response) {
        try {

            List<ExcelYsShop> excelList = new ArrayList<>();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 可以防止中文乱码
            String fileName = URLEncoder.encode("商铺报表导入模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + "." + ExcelTypeEnum.XLSX);
            EasyExcel.write(response.getOutputStream(), ExcelYsShop.class)
                    .sheet("商铺报表导入模板")
                    .registerWriteHandler(new CustomHandler())
                    .registerWriteHandler(new CellSheetWriteHandler())
                    .registerWriteHandler(new ShopCommentWriteHandler(reportRecordService))
                    .registerWriteHandler(new ShopSpinnerWriteHandler(reportRecordService))

                    .doWrite(excelList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 导入 商铺 报表
     *
     * @param file       报表文件
     * @param addOrCover 增加或者覆盖 1-增加 2-覆盖
     * @return Result
     */
    @PostMapping(value = "importShopReport")
    @ResponseBody
    public Result<Object> importShopReport(MultipartFile file, Integer addOrCover) {
        try {
            if (CheckUtil.isNull(file)) {
                return ResultUtil.errorMsg("请选择文件");
            }
            if (CheckUtil.isNull(addOrCover)) {
                return ResultUtil.errorMsg("请选择更新已有数据或不更新");
            }
            return reportRecordService.importShopReport(file, addOrCover);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 获取原始Excel
     *
     * @param reportId 原Excel的id
     * @param response HttpServletResponse
     */
    @GetMapping(value = "getOriginalExcel")
    @ResponseBody
    public void getOriginalExcel(HttpServletResponse response, Integer reportId) {
        try {
            if (CheckUtil.isNull(reportId)) {
                return;
            }
            Map<String, Object> map = reportRecordService.getErrorLogInfo(reportId);
            String excelName = CheckUtil.isNull(map.get("excelName")) ? "原始报表" : map.get("excelName").toString();
            List<ExcelYsShop> excelList = reportRecordService.getOriginalExcelUserInfo(reportId);

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 可以防止中文乱码
            String fileName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + "." + ExcelTypeEnum.XLSX);
            EasyExcel.write(response.getOutputStream(), ExcelYsShop.class)
                    .sheet(excelName)
                    .registerWriteHandler(new CustomHandler())
                    .registerWriteHandler(new CellSheetWriteHandler())
                    .registerWriteHandler(new ShopCommentWriteHandler(reportRecordService))
                    .registerWriteHandler(new ShopSpinnerWriteHandler(reportRecordService))
                    .doWrite(excelList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取错误日志报表
     *
     * @param reportId 原Excel的id
     * @param response HttpServletResponse
     */
    @GetMapping(value = "getErrorLogExcel", headers = "Accept=application/octet-stream")
    @ResponseBody
    public void getErrorLogExcel(Integer reportId, HttpServletResponse response) {
        try {
            if (CheckUtil.isNull(reportId)) {
                return;
            }
            Map<String, Object> map = reportRecordService.getErrorLogInfo(reportId);
            String excelName = CheckUtil.isNull(map.get("excelName")) ? "错误日志" : map.get("excelName").toString() + "-错误日志";
            List<ExcelYsShopError> excelUserInfoErrorList = reportRecordService.getExcelUserInfoError(reportId);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 可以防止中文乱码
            String fileName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + "." + ExcelTypeEnum.XLSX);
            EasyExcel.write(response.getOutputStream(), ExcelYsShopError.class)
                    .sheet(excelName)
                    .registerWriteHandler(new CustomHandler())
                    .registerWriteHandler(new CellSheetWriteHandler())
                    .registerWriteHandler(new ShopCommentWriteHandler(reportRecordService))
                    .registerWriteHandler(new ShopSpinnerWriteHandler(reportRecordService))
                    .doWrite(excelUserInfoErrorList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取Excel导入记录列表
     *
     * @param vo reportRecordPageVO
     * @return Result
     */
    @GetMapping(value = "getReportRecordList")
    @ResponseBody
    public Result<Object> getReportRecordList(ReportRecordPageVO vo) {
        try {
            if (CheckUtil.isNull(vo.getCurrentPage()) || CheckUtil.isNull(vo.getPageSize())) {
                return ResultUtil.errorMsg("页数和当前页不能为空");
            }
            return reportRecordService.getReportRecordList(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }


}
